package io.esirong.manager;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.util.Config;
import android.util.Log;

import java.io.File;

import androidx.core.content.FileProvider;

/**
 *
 */
public class VersionManager {

    /**
     * 安装APP应用
     *
     * @param context 上下文
     * @param file    APP文件路径
     */
    public static void installApk(Context context, File file) {
        if (file.exists()) {
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri data;

            // 兼容Android N 7.0 上 报错：android.os.FileUriExposedException
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                data = uriFromFile(context, file);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            } else {
                data = Uri.fromFile(file);
            }

            String type = "application/vnd.android.package-archive";
            intent.setDataAndType(data, type);

            // 在发出 Intent 之前必须通过 resolveActivity检查，避免找不到合适的调用组件
            if (context.getPackageManager()
                    .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {

                try {
                    context.startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    if (Config.LOGD) {
                        Log.d("VersionManager", "activity not found for "
                                + type + " over "
                                + Uri.fromFile(file).getScheme(), e);
                    }
                }
            }

        } else {
            installApkOnAppStore(context);
        }
    }

    public static void installApkOnAppStore(Context context) {
        try {
            // try to update in google store
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.getPackageName()));
            intent.setPackage("com.android.vending");
            context.startActivity(intent);
        } catch (Exception ignore) {
            //ignore
        }
    }

    /**
     * 从文件获得URI
     *  在清单配置 {LIBRARY_PACKAGE_NAME}.provider
     * @param context 上下文
     * @param file    文件
     * @return 文件对应的URI
     */
    public static Uri uriFromFile(Context context, File file) {
        Uri fileUri;
        //7.0以上进行适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String p = context.getPackageName() + ".provider";
            fileUri = FileProvider.getUriForFile(
                    context,
                    p,
                    file);
        } else {
            fileUri = Uri.fromFile(file);
        }
        return fileUri;
    }
}
